package com.echo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.echo.SportsApplication;
import com.echo.http.HttpCallBack;
import com.echo.http.HttpManager;
import com.echo.http.HttpUrl;
import com.echo.model.User;
import com.echo.util.PasswordUtil;
import com.echo.util.ToastUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

public class RegistActivity extends AppCompatActivity {

    private EditText mUsername,mPassword;
    private Button mRegist;
    private String mMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        mUsername= (EditText) findViewById(R.id.regist_username);
        mPassword= (EditText) findViewById(R.id.regist_password);
    }

    public void regist(View view){
        String username=mUsername.getText().toString();
        String password=mPassword.getText().toString();
        String url= HttpUrl.URL_REGIST+"?username="+username+"&password="+ PasswordUtil.getBase64(password);
        HttpManager.getInstance().regist(url, new HttpCallBack() {
            @Override
            public void onMsg(Object response) throws JSONException {
                JSONObject object=(JSONObject)response;
                if(object.has("message")){
                    ToastUtils.show(RegistActivity.this,object.getString("message"),Toast.LENGTH_SHORT);
                }else {
                    String json = object.toString();
                    Gson gson = new Gson();
                    User user = gson.fromJson(json, User.class);
                    SportsApplication.login(user);
                    finish();
                }
            }

            @Override
            public void onError() {
                ToastUtils.show(RegistActivity.this,"注册失败", Toast.LENGTH_SHORT);
            }
        });
    }
}
